# -*- Coding: utf-8 -*-
import cv2
import numpy as np
def charSeperate(src_img, filter_size):
    """函数功能：字符分割
       @param src_img
       @param filter_size
       @return dst_img"""
    image = cv2.imread(src_img)
    # 灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 二值化
    _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
    binary_inv = cv2.bitwise_not(binary)

    # 中值滤波
    filter_size = int(filter_size[0][0]) if filter_size else 3
    binary_f = cv2.medianBlur(binary_inv, filter_size)

    # 查找字符区域
    contours, _ = cv2.findContours(binary_f, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 遍历所有区域，寻找最大宽度
    w_max = 0
    for cnt in contours:
        _, _, w, _ = cv2.boundingRect(cnt)
        if w > w_max:
            w_max = w

    # 遍历所有区域，拼接x坐标接近的区域
    char_dict = {}
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        x_mid = x + w // 2  # 计算中点位置

        if not char_dict.keys() or all(np.abs(z - x_mid) > w_max // 2 for z in char_dict.keys()):
            char_dict[x_mid] = cnt
        else:
            for z in char_dict.keys():
                if np.abs(z - x_mid) <= w_max // 2:
                    char_dict[z] = np.concatenate((char_dict[z], cnt), axis=0)  # 拼接两个区域

    # 按照中点坐标，对字符进行排序
    char_dict = dict(sorted(char_dict.items(), key=lambda item: item[0]))

    # 遍历所有区域，提取字符
    dst_img = []
    for _, cnt in char_dict.items():
        x, y, w, h = cv2.boundingRect(cnt)
        roi = binary[y:y + h, x:x + w]
        dst_img.append(roi)

    return dst_img
